package view;
import java.awt.Color;
import java.io.File;
import java.util.ArrayList;

import model.fshare.Interface.FileTransmistObserver;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.wb.swt.SWTResourceManager;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Button;

import controller.fshare.ClientFileShareController;
import controller.fshare.Interface.ClientFileShareControl;

import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;


public class Download{
	private Display display;
	protected Shell shell;
	private Table table;
	private ToolItem toolItem_file;
	private Label label_warning;
	private Label lbl_up;
	private Label lbl_down;
	private Button btn_all;
	private Button btn_inverse;
	private ClientFileShareControl cfsc;
	
	private ShellManager sm;//窗口管理类
	
	private Image iTxt;
	private Image iWord;
	private Image iPpt;
	private Image iAccess;
	private Image iExcel;
	private Image iMusic;
	private Image iMovie;
	private Image iHtml;
	private Image iPdf;
	private Image iRar;
	private Image iPicture;
	private Image iJava;
	private Image iC;
	private Image iCpp;
	private Image iUnkown;
	
	private Up up;
	private Down down;
	
	private int upOK;
	
	private int downOKNum = 0;
	private int downFailedNum = 0;
	private int downloadingNum = 0;
	/**
	 * Launch the application.
	 * @param args
	 */
/*	public static void main(String[] args) {
		try {
			Download window = new Download();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}*/
	public Download(){
		
	}
	
	public Download(ShellManager sm){
		this.sm = sm;
	}
	/**
	 * Open the window.
	 */
	public void open() {
		display = Display.getDefault();
		cfsc = new ClientFileShareController();
		
		up = new Up();
		down = new Down();
		//初始化系统图标*********************************************************************
		iAccess = SWTResourceManager.getImage(Download.class,"/img/access_25.png");
		iC = SWTResourceManager.getImage(Download.class,"/img/c_25.png");
		iCpp = SWTResourceManager.getImage(Download.class,"/img/c++_25.png");
		iExcel = SWTResourceManager.getImage(Download.class,"/img/excel_25.png");
		iJava = SWTResourceManager.getImage(Download.class,"/img/java_25.png");
		iHtml = SWTResourceManager.getImage(Download.class,"/img/e_25.png");
		iMovie = SWTResourceManager.getImage(Download.class,"/img/movie_25.png");
		iMusic = SWTResourceManager.getImage(Download.class,"/img/mus_25.png");
		iPdf = SWTResourceManager.getImage(Download.class,"/img/pdf_25.png");
		iPicture = SWTResourceManager.getImage(Download.class,"/img/picture_25.png");
		iPpt = SWTResourceManager.getImage(Download.class,"/img/powerpoint_25.png");
		iRar = SWTResourceManager.getImage(Download.class,"/img/yasuo_25.png");
		iTxt = SWTResourceManager.getImage(Download.class,"/img/txt_25.png");
		iUnkown = SWTResourceManager.getImage(Download.class,"/img/unknown_25.png");
		iWord = SWTResourceManager.getImage(Download.class,"/img/word_25.png");		
		//初始化系统图标***结束******************************************************************
		
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}

	/**
	 * Create contents of the window.
	 * @wbp.parser.entryPoint
	 */
	protected void createContents() {
		shell = new Shell(SWT.CLOSE | SWT.MIN);
		shell.addShellListener(new ShellAdapter() {
			@Override
			public void shellClosed(ShellEvent e) {
				e.doit = false;
				sm.setShareOpen(false);
				SlowlyDisappear(shell, 440, 291, shell.getLocation().x, shell.getLocation().y);
			}
		});
		shell.setText("群共享");
		shell.setImage(SWTResourceManager.getImage(Download.class, "/img/GMS.png"));
		shell.setSize(440, 291);
		shell.setLocation(sm.getDownload_x(),sm.getDownload_y());
		
		label_warning = new Label(shell, SWT.NONE);
		label_warning.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		label_warning.setAlignment(SWT.CENTER);
		label_warning.setBounds(15, 235, 385, 20);
		label_warning.setVisible(false);
		
		lbl_up = new Label(shell, SWT.NONE);
		lbl_up.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		lbl_up.setAlignment(SWT.CENTER);
		lbl_up.setVisible(false);
		lbl_up.setBounds(15, 235, 385, 20);
		
		lbl_down = new Label(shell, SWT.NONE);
		lbl_down.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		lbl_down.setAlignment(SWT.CENTER);
		lbl_down.setVisible(false);
		lbl_down.setBounds(15, 235, 385, 20);
		
		table = new Table(shell, SWT.BORDER | SWT.CHECK | SWT.FULL_SELECTION | SWT.MULTI);
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDown(MouseEvent e) {
				Point point = new Point(e.x,e.y);
				//决定鼠标在哪一行，哪一列
				if(table.getItem(point) != null){
					Rectangle rect = table.getItem(point).getBounds(1);				
					if(!rect.contains(point)){
						btn_all.setSelection(false);
						btn_inverse.setSelection(false);
					}
				}
			}
		});
		table.setLinesVisible(true);
		table.setBounds(10, 52, 414, 206);
		
		
		TableColumn tableColumn_check = new TableColumn(table, SWT.LEFT);
		tableColumn_check.setResizable(false);
		tableColumn_check.setWidth(35);
		
		
		TableColumn tableColumn_name = new TableColumn(table, SWT.NONE);
		tableColumn_name.setResizable(false);
		tableColumn_name.setWidth(357);
		
		if(cfsc.getAllSharedFilesName() != null){
			for(String str : cfsc.getAllSharedFilesName()){
				TableItem ti = new TableItem(table, SWT.NONE);
				ti.setImage(1,getFileIcon(str));
				ti.setText(1,str);
			}
		}
			
		final ToolBar toolBar = new ToolBar(shell, SWT.FLAT | SWT.RIGHT);
		toolBar.setBounds(10, 8, 300, 40);	
		toolItem_file = new ToolItem(toolBar, SWT.NONE);	
		toolItem_file.setText("上传");
		toolItem_file.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if(lbl_up.isVisible()){
					return;
				}			
				FileDialog fd = new FileDialog(shell, SWT.OPEN);
				fd.open();
				//System.out.println(fd.getFilterPath() + "\\" + fd.getFileName());
				if(!fd.getFilterPath().equals("")){					
					File file = new File(fd.getFilterPath() + "\\" + fd.getFileName());
					lbl_up.setText("上传中...");
					lbl_up.setVisible(true);
					if(lbl_down.isVisible()){
						lbl_up.setBounds(15, 210, 385, 20);
					}
					else{
						lbl_up.setBounds(15, 235, 385, 20);
					}
					upOK = cfsc.upload(file ,up);
					if(upOK == 2){
						lbl_up.setText("上传失败，请不要上传同名文件");
						UpDownThread udt = new UpDownThread(lbl_up);
						udt.start();
					}
					else if(upOK == 1){
						lbl_up.setText("上传失败，您选择的文件不存在");
						UpDownThread udt = new UpDownThread(lbl_up);
						udt.start();
					}
					else if(upOK == 3){
						lbl_up.setText("某种未知错误导致上传失败");
						UpDownThread udt = new UpDownThread(lbl_up);
						udt.start();
					}
				}
				
			}
		});
		toolItem_file.setToolTipText("");
		toolItem_file.setImage(SWTResourceManager.getImage(Download.class, "/img/\u4E0A\u4F20\u6587\u4EF6_30.png"));
		
		ToolItem toolItem_sep0 = new ToolItem(toolBar, SWT.SEPARATOR);
		
		
		ToolItem toolItem_refresh = new ToolItem(toolBar, SWT.NONE);
		toolItem_refresh.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				refresh();
				BackgroundThread bt = new BackgroundThread("刷新成功");
				bt.start();
			}
		});
		toolItem_refresh.setText("刷新");
		toolItem_refresh.setImage(SWTResourceManager.getImage(Download.class, "/img/\u5237\u65B0_30.png"));
		
		ToolItem toolItem_sep1 = new ToolItem(toolBar, SWT.SEPARATOR);
		
		ToolItem toolItem_del = new ToolItem(toolBar, SWT.NONE);
		toolItem_del.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {							
				TableItem[] items = table.getItems();
				int successNum = 0;
				int failedNum = 0;
				//多行删除的算法
				int k = 0;
				for(int i=0;i < items.length;i++){
					if(items[i].getChecked()){
						if(cfsc.delete(items[i].getText(1))){
							successNum ++;
							table.remove(i-k);
							k++;
						}
						else{
							failedNum ++;
						}
					}
				}
				if(successNum==0 && failedNum==0){
					BackgroundThread bt = new BackgroundThread("请选择文件");
					bt.start();
				}
				else{
					BackgroundThread bt = new BackgroundThread(successNum + "个文件删除成功，"
															+ failedNum + "个文件为其他人上传");
					bt.start();
				}
			}
		});
		toolItem_del.setText("删除");
		toolItem_del.setImage(SWTResourceManager.getImage(Download.class, "/img/del_30.png"));
		
		ToolItem toolItem_sep2 = new ToolItem(toolBar, SWT.SEPARATOR);
		
		ToolItem toolItem_down = new ToolItem(toolBar, SWT.NONE);
		toolItem_down.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {			
				if(lbl_down.isVisible()){
					return;
				}
				int failedDownNum = 0;
				
				if(lbl_up.isVisible()){
					lbl_down.setBounds(15, 210, 385, 20);
				}
				else{
					lbl_down.setBounds(15, 235, 385, 20);
				}
				
				TableItem[] items = table.getItems();
				for(int i=0;i<items.length;i++){
					if(items[i].getChecked()){
						if(cfsc.download(items[i].getText(1),down)){
							downloadingNum ++;
						}
						else{
							failedDownNum ++;
						}
					}
				}
				if(downloadingNum == 0){
					if(failedDownNum != 0){
						lbl_down.setText(failedDownNum + "个文件已存在");
						lbl_down.setVisible(true);
						UpDownThread udt = new UpDownThread(lbl_down);
						udt.start();
					}
					else{
						lbl_down.setText("请选择文件");
						lbl_down.setVisible(true);
						UpDownThread udt = new UpDownThread(lbl_down);
						udt.start();
					}
				}
				else{
					lbl_down.setText(downloadingNum + "个文件下载中..." + failedDownNum + "个文件已存在");
					lbl_down.setVisible(true);
				}
			}
		});
		toolItem_down.setImage(SWTResourceManager.getImage(Download.class, "/img/download_30.png"));
		toolItem_down.setText("下载");
		
		btn_all = new Button(shell, SWT.CHECK);
		btn_all.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				TableItem[] items = table.getItems();
				if(items == null){
					return;
				}
				if(btn_all.getSelection()){
					for(int i=0;i<items.length;i++){
						items[i].setChecked(true);
					}
				}
				else{
					for(int i=0;i<items.length;i++){
						items[i].setChecked(false);
					}
				}
				btn_inverse.setSelection(false);
			}
		});
		btn_all.setBounds(321, 20, 50, 17);
		btn_all.setText("全选");
		
		btn_inverse = new Button(shell, SWT.CHECK);
		btn_inverse.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				TableItem[] items = table.getItems();
				if(items == null){
					return;
				}
				for(int i=0;i<items.length;i++){
					if(items[i].getChecked()){
						items[i].setChecked(false);
					}
					else{
						items[i].setChecked(true);
					}
				}
				int selectionNum = 0;
				for(int i=0;i<items.length;i++){
					if(items[i].getChecked()){
						selectionNum ++;
					}
				}
				if(selectionNum == 0){
					btn_all.setSelection(false);
				}
				else if(selectionNum == items.length){
					btn_all.setSelection(true);
				}
			}
		});
		btn_inverse.setBounds(374, 20, 50, 17);
		btn_inverse.setText("反选");
		
	}
	//label提示框后台线程********************************************************************************
	class BackgroundThread extends Thread{
		String str = "";
		public BackgroundThread(String str){
			this.str = str;
		}
		public void run(){
			display.asyncExec(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					label_warning.setText(str);
					label_warning.setVisible(true);
				}
			});
			try {
				sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(!label_warning.isDisposed()){
				display.asyncExec(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						label_warning.setVisible(false);
					}
				});
			}
		}
	}
	//label提示框后台进程********************************************************************************
	
	class UpDownThread extends Thread{
		private Label lbl;
		public UpDownThread(Label lbl){
			this.lbl = lbl;
		}
		public void run(){
			try {
				sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if(!lbl.isDisposed()){
				display.asyncExec(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						lbl.setVisible(false);
						if(lbl_down.isVisible()){
							lbl_down.setBounds(15, 235, 385, 20);
						}
						else{
							lbl_up.setBounds(15, 235, 385, 20);
						}
					}
				});
			}
		}
	}
	
	
	//刷新列表的方法************************************************************************************
	private void refresh(){
		table.clearAll();
		TableItem[] items = table.getItems();
		int count = 0;
		for(String str : cfsc.getAllSharedFilesName()){
			if(count < items.length){
				items[count].setImage(1,getFileIcon(str));
				items[count].setText(1,str);
			}
			else{
				TableItem ti =new TableItem(table, SWT.NONE);
				ti.setImage(1,getFileIcon(str));
		    	ti.setText(1,str);
		    }
			count ++;
	    }
	}
	//刷新列表的方法***结束*********************************************************************************
	
	//根据后缀名返回图标********************************************************************************
	private Image getFileIcon(String str){//文件名
		String suffix = str.substring(str.lastIndexOf(".") + 1);
		if(suffix.equalsIgnoreCase("mdb")){
			return iAccess;
		}
		else if(suffix.equalsIgnoreCase("c")){
			return iC;	
		}
		else if(suffix.equalsIgnoreCase("cpp")){
			return iCpp;	
		}
		else if(suffix.equalsIgnoreCase("xls")||suffix.equalsIgnoreCase("xlsx")){
			return iExcel;
		}
		else if(suffix.equalsIgnoreCase("java")){
			return iJava;	
		}
		else if(suffix.equalsIgnoreCase("html")){
			return iHtml;	
		}
		
		else if(suffix.equalsIgnoreCase("rmvb")||suffix.equalsIgnoreCase("mkv")||suffix.equalsIgnoreCase("mp4")
				||suffix.equalsIgnoreCase("avi")||suffix.equalsIgnoreCase("wmv")){
			return iMovie;
		}

		else if(suffix.equalsIgnoreCase("mp3")||suffix.equalsIgnoreCase("wma")){
			return iMusic;
		}
		
		else if(suffix.equalsIgnoreCase("pdf")){
			return iPdf;
		}
		else if(suffix.equalsIgnoreCase("png")||suffix.equalsIgnoreCase("jpg")||suffix.equalsIgnoreCase("bmp")){
			return iPicture;
		}
		else if(suffix.equalsIgnoreCase("ppt")||suffix.equalsIgnoreCase("pptx")){
			return iPpt;
		}
		else if(suffix.equalsIgnoreCase("rar")||suffix.equalsIgnoreCase("zip")){
			return iRar;
		}
		else if(suffix.equalsIgnoreCase("txt")){
			return iTxt;
		}
		else if(suffix.equalsIgnoreCase("doc")||suffix.equalsIgnoreCase("docx")){
			return iWord;
		}
		
		else{
			return iUnkown;
		}
	}
	//根据后缀名返回图标***结束*****************************************************************************
	
	
	private class Up implements FileTransmistObserver{

		@Override
		public void update() {
			// TODO Auto-generated method stub
			display.asyncExec(new Runnable() {
				
				@Override
				public void run() {
					//System.out.println("上传update");
					// TODO Auto-generated method stub
					lbl_up.setText("上传成功！提示栏即将关闭");
					lbl_up.setVisible(true);
					UpDownThread udt = new UpDownThread(lbl_up);
					udt.start();
					refresh();
				}
			});
		}

		@Override
		public void failed() {
			// TODO Auto-generated method stub
			display.asyncExec(new Runnable() {
				
				@Override
				public void run() {
					//System.out.println("上传update");
					// TODO Auto-generated method stub
					lbl_up.setText("上传失败！请检查您的文件名");
					lbl_up.setVisible(true);
					UpDownThread udt = new UpDownThread(lbl_up);
					udt.start();
					refresh();
				}
			});
		}
		
	}
	private class Down  implements FileTransmistObserver{

		@Override
		public void update() {
			downloadingNum --;
			downOKNum ++;
			// TODO Auto-generated method stub
			display.asyncExec(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					if(downloadingNum != 0){
						lbl_down.setText(downloadingNum + "个文件下载中..." + downOKNum + "个文件下载成功" + downFailedNum + "个文件下载失败");
						lbl_down.setVisible(true);
						refresh();
					}
					else{
						if(downFailedNum == 0){
							lbl_down.setText(downOKNum + "个文件下载成功！");
							lbl_down.setVisible(true);
							UpDownThread udt = new UpDownThread(lbl_down);
							udt.start();
							refresh();
						}
						else{
							lbl_down.setText(downOKNum + "个文件下载成功！" + downFailedNum + "个文件下载失败");
							lbl_down.setVisible(true);
							
							UpDownThread udt = new UpDownThread(lbl_down);
							udt.start();
							refresh();
						}
						downOKNum = 0;
						downFailedNum = 0;
					}
				}
			});
		}

		@Override
		public void failed() {
			// TODO Auto-generated method stub

			downloadingNum --;
			downFailedNum ++;
			// TODO Auto-generated method stub
			display.asyncExec(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					if(downloadingNum != 0){
						lbl_down.setText(downloadingNum + "个文件下载中..." + downOKNum + "个文件下载成功" + downFailedNum + "个文件下载失败");
						lbl_down.setVisible(true);
						refresh();
					}
					else{
						if(downOKNum == 0){
							lbl_down.setText(downOKNum + "个文件下载失败");
							lbl_down.setVisible(true);
							UpDownThread udt = new UpDownThread(lbl_down);
							udt.start();
							refresh();
						}
						else{
							lbl_down.setText(downOKNum + "个文件下载成功！"+ downFailedNum + "个文件下载失败");
							lbl_down.setVisible(true);
							UpDownThread udt = new UpDownThread(lbl_down);
							udt.start();
							refresh();
						}
						downOKNum = 0;
						downFailedNum = 0;
					}
				}
			});
		}
		
	}
	
	//慢慢消失之缩点********************************************************************************************
	public void SlowlyDisappear(final Shell shell,final int width,final int height,final int startX,final int startY){
		new Thread(new Runnable() {
			private int startWidth = width;
		    private int startHeight = height;
		    
		    public void run() {
		        while (startWidth > 88){
		            shell.getDisplay().syncExec(new Runnable() {
		                public void run() {
		                	startWidth = startWidth - 44;
		                	startHeight = startHeight - 29;
		                	
		                	shell.setLocation(startX + (width - startWidth)/2, startY + (height - startHeight)/2);
		                	shell.setSize(startWidth, startHeight);
		                	
		                	/*System.out.println("w"+startWidth);
		                	System.out.println("h"+startHeight);
		                	System.out.println("x"+(startX + (width - startWidth)/2));
		                	System.out.println("y"+(startY + (height - startHeight)/2));*/
		                }
		            });
		            Thread.yield();// 暂停
		        } 
		        shell.getDisplay().syncExec(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						shell.setVisible(false);
						shell.dispose();
					}
		        	
		        });
		        
		    }
		}).start();
	}
	//慢慢消失之缩点***结束*****************************************************************************************
}
